/* eslint-disable no-unused-vars */
const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');

const files = process.argv.slice(2);
const standardTime = new Date('2019-09-15').getTime() / 1000;

const ignoreList = [
    'app/',
    'res/js/',
    'dist/',
    'src/modules/Touch',
    'src/views/newRecommend/viewWin/index.js',
    'src/views/newRecommend/detail/viewWin/index.js',
];

// 必须要校验的文件夹列表
const needCheckList = [
    'src/main',
    'src/modules',
    'src/components',
    'src/views/live',
    'src/views/cloudWarehouse',
    'src/views/promotionCenter',
    // 'src/views/pay',
];

const eslintConfigPath = path.resolve(process.cwd(), './.eslintrc.base.js');

function lintLog(...args) {
    console.log('webApp lintLog::', ...args);
}

function checkBranch() {
    const branchName = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' }).trim();
    lintLog('当前分支为', branchName);
    if (/^(gray|t\d+|master)$/.test(branchName)) {
        process.exit(0);
    }
}

function formatAndLint(needFormatFiles = []) {
    if (needFormatFiles.length === 0) {
        return;
    }
    lintLog('正在校验文件', ...needFormatFiles);
    const cmd = [
        `eslint --no-eslintrc -c ${eslintConfigPath} --quiet --fix ${needFormatFiles.join(' ')}`,
        `prettier --parser babel --write ${needFormatFiles.join(' ')}`,
        `git add ${needFormatFiles.join(' ')}`,
    ]
        .filter((i) => i)
        .join(' && ');

    try {
        execSync(cmd, { stdio: 'inherit' });
    } catch (err) {
        // lintLog('lint Fail', ...needFormatFiles);
        process.exit(1);
    }
}

// 获取文件添加时间
function getLastAddTime(file = '') {
    return Number(execSync(`git log --format=%at ${file} | tail -1`, { encoding: 'utf8' }).trim()) || Infinity;
}

checkBranch();

formatAndLint(
    files.filter(
        (file) =>
            !ignoreList.some((i) => file.includes(i)) && // 忽略文件夹不校验
            fs.existsSync(file) && // 文件必须存在
            (needCheckList.some((i) => file.includes(i)) || // 或者是已经被eslint修复过的文件夹
                getLastAddTime(file) > standardTime) // 时间在指定时间节点之后
    )
);
